// pages/judge/index.js
var maxTextLength = 140
var maxImageNum = 4
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    restLength: maxTextLength,
    activeIndex: -1,
    avatarUrl: [],
    starList: [5 * '/images/judge/icon_star'],
    product: {},
    imgUrl: app.globalData.imgUrl,
    comment: '',
    fileIDList: [],
    index: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    console.log(e.product)
    let productTemp = JSON.parse(e.product)
    productTemp.pic = this.data.imgUrl + productTemp.pic
    this.setData({
      product: productTemp,
      index: e.index
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 
   */
  bindInput: function (e) {
    var inputLength = this.getLength(e.detail.value)
    //console.log(e.detail.value)
    this.setData({
      restLength: maxTextLength - inputLength,
      comment: e.detail.value
    })
  },

  getLength: function (str) {
    return str.length;
  },

  starTap: function (e) {
    this.setData({
      activeIndex: e.currentTarget.dataset.index
    })
  },

  deleteImage: function (e) {
    var tempavatarUrl = this.data.avatarUrl
    var tempFileIDList = this.data.fileIDList
    tempavatarUrl.splice(e.currentTarget.dataset.index, 1)
    tempFileIDList.splice(e.currentTarget.dataset.index, 1)

    //console.log(e.currentTarget.index)
    this.setData({
      avatarUrl: tempavatarUrl,
      fileIDList: tempFileIDList
    }) 
  },


  bindViewTap: function () {
    var that = this;
    wx.chooseImage({
      // 设置最多可以选择的图片张数，默认9,如果我们设置了多张,那么接收时//就不在是单个变量了,
      count: 1,
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        // 获取成功,将获取到的地址赋值给临时变量
        //var tempFilePaths = res.tempFilePaths;
        var tempavatarUrl = that.data.avatarUrl

        that.uploadImage(res.tempFilePaths[0])

        tempavatarUrl.push(res.tempFilePaths[0])
        that.setData({
          //将临时变量赋值给已经在data中定义好的变量
          avatarUrl: tempavatarUrl
        })
      },
      fail: function (res) {
        // fail
      },
      complete: function (res) {
        // complete
      }
    })
  },

  submitTap: function () {
    if (this.data.activeIndex > 0)
      this.uploadComment()
    else 
      wx.showModal({
        title: '提示',
        content: '请为商品评分',
        showCancel: false
      })
  },

  /**
   * 上传评论
   */
  uploadComment: function () {
    let token = wx.getStorageSync('token')
    let that = this
    console.log(that.data.fileIDList)
    wx.request({
      url: app.apiUrl('/user/comment'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        order_id: that.data.product.order_id,
        product_id: that.data.product.product_id,
        product_sku_id: that.data.product.product_sku_status == 1 ? that.data.product.product_sku_id : 0,
        star: parseInt(that.data.activeIndex) + 1,
        content: that.data.comment,
        file: that.data.fileIDList
      },
      success: function (res) {
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          console.log('uploadcomments')
          console.log(res.data)
          if (res.data.data) {
            wx.showToast({
              title: res.data.data,
              icon: 'none',
              duration: 2000
            })
          }
          let pages = getCurrentPages();
          let prevPage = pages[pages.length - 2];
          prevPage.changeCommentStatus(that.data.index)
          wx.navigateBack({
            delta: 1
          })
          
        }
    
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false
        })
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  uploadImages: function () {
    for (var i = 0; i < this.data.avatarUrl.length; i++) {
      wx.uploadFile({
        url: app.apiUrl('/user/uploadfile'),
        filePath: this.data.avatarUrl[i],
        name: 'file',
        formData: {
          'user': 'test'
        },
        success: function (res) {
          var data = res.data
          console.log(res.data)
          
        }
      })
    }
  },

  uploadImage: function (filePath) {
    let token = wx.getStorageSync('token')
    let that = this
    wx.uploadFile({
      header: {
        "Authorization": 'Bearer ' + token
      },
      url: app.apiUrl('/user/uploadfile'),
      filePath: filePath,
      
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (res) {
        var data = JSON.parse(res.data)
        var tempFileIDList = that.data.fileIDList
        console.log(res)
        if (data.data) {
          console.log(data.data.fileId)
          tempFileIDList.push(data.data.fileId + "")
          that.setData({
            fileIDList: tempFileIDList
          })
        }
      }
    })
    
  },

  

})